package com.atom.common.delegate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.activiti.engine.task.Task;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.atom.common.DelegateAction;
import com.atom.common.DelegateStatus;
import com.atom.common.DelegateType;
import com.atom.common.VariablesConstant;
import com.atom.common.activiti.ActivitiHandler;
import com.atom.common.remote.palace.RemoteRunningTaskDao;

/**
 * Title: AddCoopDelegateHandler
 * Description: 添加协同代理
 * @author WEWE
 * @date 2017年12月4日 下午3:17:12
 * @version 1.0
 */
@Component
@Transactional
public class AddCoopDelegateHandler {
  
  private static Logger logger = Logger.getLogger(AddCoopDelegateHandler.class);

  @Resource DelegateInfoDao delegateInfoDao;
  @Resource DelegateLogDao delegateLogDao;
  @Resource ActivitiHandler activitiHandler;
  @Resource RemoteRunningTaskDao remoteRunningTaskDao;

  public void add(DelegateInfo info) {
    logger.info("DelegateInfo:Id:" + info.getId());
    logger.info("DelegateInfo:DelegateStatus:" + info.getDelegateStatus());
    logger.info("DelegateInfo:Owner:" + info.getOwner());
    logger.info("DelegateInfo:Assignee:" + info.getAssignee());
    List<Map<String, String>> list = new ArrayList<Map<String, String>>();
    // 将状态改为处理中
    info.setDelegateStatus(DelegateStatus.ADD_DOING);
    delegateInfoDao.update(info);
    // 被代理人
    String owner = info.getOwner();
    // 代理人
    String assignee = info.getAssignee();
    // 公文类型
    String processDefKey = info.getProcessDefinitionKey();
    // 获取被代理人的任务列表
    List<Task> taskList = activitiHandler.findTaskListByUserByProcessDefKey(owner, processDefKey);
    for (Task task : taskList) {
      if (activitiHandler.taskHasUser(task.getId(), assignee)) {
        continue;
      }
        // 添加任务候选人
        activitiHandler.addCandidate(task.getId(), assignee);
        task.setOwner(assignee);
        // 记录操作日志
        DelegateLog log = new DelegateLog(info.getId(), task.getId(), owner, assignee, DelegateType.COOP);
        delegateLogDao.save(log);
        // 改平台待办表
        Map<String, String> re = new HashMap<String, String>();
        String sysModID = (String) activitiHandler.findVariableByTaskIdByKey(task.getId(), VariablesConstant.SYSTEM_MODULER);
        re.put("ACTIVITYENTITYID", sysModID + "_" + processDefKey + "_" + task.getId());
        re.put("SYSMODID", sysModID);
        re.put("owner", owner);
        re.put("assignee", assignee);
        re.put("delegateType", DelegateType.COOP + "");
        list.add(re);
    }
    // 将状态改为已完成
    info.setDelegateStatus(DelegateStatus.ADD_DONE);
    delegateInfoDao.update(info);
    remoteRunningTaskDao.updateTodoTasksForDelegate(list, DelegateAction.ADD);
  }

}
